package com.lnlyj.media.base;

import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * Create By Lnlyj on 2019/11/29
 **/
public abstract class BaseAdapter<Data,VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter {

    private List<Data> list = new ArrayList<>();

    protected OnItemClickListener<Data> onItemClickListener;

    public interface OnItemClickListener<Data> {
        void onItemClick(Data data, int position);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return getViewHolder(parent, viewType);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        bindData((VH) holder, position);
    }

    public abstract VH getViewHolder(@NonNull ViewGroup parent, int viewType);
    public abstract void bindData(VH holder, int position);

    public Data getItem(int position) {
        return list.get(position);
    }

    public List<Data> getList() {
        return list;
    }

    public void swapResult(List<Data> result) {
        this.list.clear();
        addAll(result);
    }

    public void addData(Data data) {
        this.list.add(data);
        notifyDataSetChanged();
    }

    public void addData(int index, Data data) {
        this.list.add(index, data);
        notifyDataSetChanged();
    }

    public void addAll(List<Data> list) {
        if (list != null && !list.isEmpty()) {
            this.list.addAll(list);
        }
        notifyDataSetChanged();
    }

    public void setOnItemClickListener(OnItemClickListener<Data> onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }
}
